'use strict'

const Controller = require('egg').Controller

class CommentsController extends Controller {
	async index() {
		const { ctx } = this
		ctx.body = 'hi, egg'
	}
	// 添加评论 （谁 评论 哪个文章）
	async addComments() {
		const { ctx, app } = this
		const { blogsId, userId, content } = ctx.request.body
		// const errors = app.validator.validate(
		// 	{
		// 		blogsId: 'string' | 'number',
		// 		userId: 'string' | 'number',
		// 		content: 'string'
		// 	},
		// 	ctx.request.body
		// )

		const addComData = await app.mysql.insert('comments', {
			blogsId,
			userId,
			content
		})
		if (addComData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '添加成功',
				data: { insertId: addComData.insertId }
			}
		} else {
			ctx.body = { code: 0, msg: '添加失败，请重试' }
		}
	}

	// 删除评论
	async removeComments() {
		const { ctx, app } = this
		const { commentsId } = ctx.params
		const removeData = await app.mysql.delete('comments', { commentsId })
		if (removeData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '删除成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '删除失败，请重新尝试'
			}
		}
	}

	// 修改评论
	async updateComments() {
		const { ctx, app } = this
		const { commentsId } = ctx.params
		const { content } = ctx.request.body
		const row = {
			content
		}
		const options = {
			where: {
				commentsId
			}
		}
		const result = await app.mysql.update('comments', row, options)
		if (result.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '失败，请重新尝试'
			}
		}
	}

	// 查询评论
	async queryComments() {
		const { ctx, app } = this
		const { page, size } = ctx.query
		try {
			// 参数校验
			const errors = app.validator.validate(
				{ page: 'string', size: 'string' },
				ctx.query
			)
			if (!errors) {
				console.log(errors, 'errors=================>')
				const result = await app.mysql.select('comments', {
					limit: size * 1,
					offset: (page - 1) * size
				})
				ctx.body = { code: 0, msg: 'success', data: result }
			} else {
				ctx.body = { code: -1 }
			}
		} catch (err) {
			ctx.body = {
				code: -1,
				msg: err
			}
		}
	}
}

module.exports = CommentsController
